<?php

namespace common\models;

use console\controllers\FeehiCmsController;
use Guzzle\Http\Exception\ServerErrorResponseException;
use Yii;
use yii\web\ServerErrorHttpException;

/**
 * This is the model class for table "vip_assignment".
 *
 * @property string           $item_name
 * @property string           $user_id
 * @property int              $availability_num 可使用次数
 * @property int              $expired_time 过期时间
 * @property int              $created_at
 *
 * @property VipItem          $itemName
 * @property \api\models\User $user
 */
class VipAssignment extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'vip_assignment';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['item_name', 'user_id'], 'required'],
            [['availability_num', 'expired_time', 'created_at'], 'integer'],
            [['item_name', 'user_id'], 'string', 'max' => 64],
            [['item_name', 'user_id'], 'unique', 'targetAttribute' => ['item_name', 'user_id']],
            [
                ['item_name'],
                'exist',
                'skipOnError'     => true,
                'targetClass'     => VipItem::className(),
                'targetAttribute' => ['item_name' => 'name']
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'item_name'        => '名称',
            'user_id'          => '用户id',
            'availability_num' => '可使用次数',
            'expired_time'     => '过期时间',
            'created_at'       => '分配时间',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getItemName()
    {
        return $this->hasOne(VipItem::className(), ['name' => 'item_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(\api\models\User::className(), ['id' => 'user_id']);
    }


    public function beforeSave($insert)
    {
        if ($insert) {
            $this->created_at = time();
        }

        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }


    /**
     * @param Order $order
     *
     * @return bool
     */
    public static function assignRightFromOrderToUser(Order $order)
    {
        $uid    = $order->uid;
        $good   = $order->good;
        $num    = empty($order->number) ? 1 : $order->number;
        $item   = $good->right0->item_name;
        $assign = VipAssignment::findOne(['item_name' => $item, 'user_id' => $uid]);
//        var_dump($assign);
//        var_dump($good->right0->item_name);
        //以分配权限
        if ($assign) {
            $assign->availability_num += $num * $good->availability_num;
            $assign->expired_time     += $num * $good->availability_period;
            //未分配权限创建新的权限
        } else {
            $assign                   = new VipAssignment();
            $assign->availability_num = $num * $good->availability_num;
            $assign->expired_time     = time() + $num * $good->availability_period;
        }
        $assign->item_name = $good->right0->item_name;
        $assign->user_id   = Yii::$app->getUser()->id;

//        var_dump($assign->save(false));
        return $assign->save(false);

    }


    /**
     * @param $user_id
     * @param $item_name
     *
     * @return bool
     */
    public static function can($user_id, $item_name)
    {
        $assignment = VipAssignment::findOne(['item_name' => $item_name, 'user_id' => $user_id]);
        if ($assignment->availability_num > 0 && $assignment->expired_time > time()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @param $user_id
     * @param $item_name
     *
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function useRight($user_id, $item_name)
    {
        $assignment = VipAssignment::findOne(['item_name' => $item_name, 'user_id' => $user_id]);
        if (VipAssignment::can($user_id, $item_name)) {
            $assignment->availability_num--;

            return $assignment->save();
        } else {
            if ($assignment != null) {
                $assignment->delete();
            }
            return false;

        }
    }

}
